$(function() {
    var qrmLoginMethod = 'mobile';
    var qrmRoomSynTemplete = $('#synQrmRoom');
    var qrmRoomSynedTemplete = $('#synedQrmRoom');
    var RFRoomSynedTemplete = $('#synedRFRoom');
    var synedQrbRoomTemplete = $('#synedQrbRoom');
    //钟点房 长租房 基础房型切换
    $('.room-tab-index').click(function () {
        $(this).blur().addClass('btn-primary').siblings().removeClass('btn-primary');
        $('#room-index').removeClass('hidden').siblings(":not(':first')").addClass('hidden');
        $('.hotel-content').removeClass('hidden');
        $('#content-panel-show').removeClass('hidden');
    });
    // 切换锁掌柜登录方式
    $('#qrmLoginTypeMobile').on('click', function() {
        qrmLoginMethod = 'mobile';
        $('#qrmLoginEmailContainer').addClass('hidden');
        $('#qrmLoginMobileContainer').removeClass('hidden');
        $('#qrmLoginNameMobile').trigger('select');
    });
    $('#qrmLoginTypeEmail').on('click', function() {
        qrmLoginMethod = 'email';
        $('#qrmLoginMobileContainer').addClass('hidden');
        $('#qrmLoginEmailContainer').removeClass('hidden');
        $('#qrmLoginNameEmail').trigger('select');
    });
    // 切换添加客栈方式
    window.addStyles = false;
    $('.addHotel').on('click', function() {
        $('.charity').removeClass('activehotel');
        $(this).addClass('activehotel');
        $('.smalltip').removeClass('hidden');
        window.addStyles = true;
    });    
    $('.charity').on('click', function() {
        $('.addHotel').removeClass('activehotel');
        $(this).addClass('activehotel');
        $('.smalltip').addClass('hidden');
        window.addStyles = false;
    });    
    // 添加可同步锁掌柜房间的提示,添加点击事件
    var refreshQrmSynRoom = function() {
        $('.roomNameTag').each(function() {
            var me = $(this);
            me.find('.roomNameTagTip').remove();
            if ($.inArray(me.text().trim(), window.qrmInit) >= 0) {
                if (me.data('syn') === 0) {
                    me.append(qrmRoomSynTemplete.html());
                    me.addClass('canSyn');
                } else if (me.data('syn') === 1 || me.data('syn') === 3) {
                    me.append(qrmRoomSynedTemplete.html());
                    me.addClass('syned');
                } else if(me.data('syn') === 2) {
                    me.append(RFRoomSynedTemplete.html());
                    me.addClass('syned');
                }else if(me.data('syn') === 5) {
                    me.append(synedQrbRoomTemplete.html());
                    me.addClass('syned');
                }
            }
        });
    };
    refreshQrmSynRoom();
    $('.roomNameTag').on('click', function() {
        var me = $(this);
        if (!me.hasClass('canSyn')) {
            return;
        }
        $('#submitSynQrmRoom').data('value', me.data('value'));
        formInlineRight($('#submitSynQrmRoom'));
        $('#synQrmRoomModal').modal('show');
    });

    // 同步单个锁掌柜房间
    $('#submitSynQrmRoom').on('click', function() {
        var me = $(this),
            param = {
                hotel: window.currentHotel,
                roomId: me.data('value')
            };
        ajaxRequest('/Home/Room/synRoom', param, 'post', null, null, me);
    });

    // 刷新锁掌柜可选房间
    var refreshQRMContainer = function(modal) {
        // 计算已选的房间或者是已输入的房间
        var selectedRoom = $.grep(window.init, function(index) {
            return $.inArray(index, window.dynamicRoom) === -1;
        });
        var avaliableRooms = [];
        if (window.qrmInit.length !== 0) {
            modal.find('.roomNumInput').each(function(index) {
                var value = $(this).val();
                if (value !== '' && $.inArray(value, selectedRoom) === -1) {
                    selectedRoom.push(value);
                }
            });
            // 计算可选的锁掌柜房间
            $.each(window.qrmInit, function(index, name) {
                if ($.inArray(name, selectedRoom) === -1) {
                    avaliableRooms.push(name);
                }
            });
        }
        // 分情况渲染页面
        if (avaliableRooms.length === 0) {
            modal.find('.synchronousRoomGroup').addClass('hidden');
        } else {
            modal.find('.synchronousRoomGroup').removeClass('hidden');
            var tagsData = [];
            $.each(avaliableRooms, function(index, name) {
                tagsData.push({
                    id: name,
                    name: name
                });
            });
            var roomContainer = modal.find('.synchronousRoomContainer');
            var data = roomContainer.data('amos.tag');
            if (!data) {
                roomContainer.tag({
                    removeAtSelected: true,
                    selectedTagClickable: false,
                    avaliable: tagsData
                }).on('beforeSelected.amos.tag', function(e, value) {
                    var templete = $(addRoomTemplate.clone().html());
                    templete.find('input.roomNumInput').attr('value', value);
                    var container = $(this);
                    var modal = container.parents('.modal');
                    modal.find('.roomNumContainer').append(templete.prop('outerHTML'));
                    // 如果可同步房间是最后一个就隐藏，注意是beforeSelected，所以判断是1
                    if (container.find('.tag-avaliable-container .tag').length === 1) {
                        modal.find('.synchronousRoomGroup').addClass('hidden');
                    }
                });
            } else {
                roomContainer.tag('resetAvaliable');
                roomContainer.tag('addAvaliable', tagsData);
            }
        }
    };
    // 添加客栈自动校验
    $('#addHotelModal').inputValidate({
        submit: {
            query: '#submitAddHotel'
        },
        inputs: [{
            query: '#hotelName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('dealer.name'),
            emptyMessage: lang('tip.popularizeNull')
        }]
    });

    // 初始化新客栈区号为中国
    var chinaSelectOptionValue = $("#addHotelModal #addRequestUniversalTime").find('option[data-areacode=86]').val();
    $("#addRequestUniversalTime").val(chinaSelectOptionValue);

    // 添加客栈
    $('#submitAddHotel').on('successSubmit.amos.inputValidate', function(e) {
        var param = {
                hotel: $('#hotelName').val().trim(),
                city: $('#cityContainer').find('.tag-selected-container .tag:last-child').data('value'),
                district: $('#districtContainer').find('.tag-selected-container .tag:first-child').data('value'),
                universalTime: $('#addHotelModal #addRequestUniversalTime').val(),
                currencyId: $('#addHotelModal #addRequestMultiCurrency').val()
            },
            $me = $(this);
        if (!param.city || !param.district) {
            formInlineTip($me, lang('dealer.checkAddress'));
            return false;
        }
        formInlineRight($me);
        if(window.addStyles){
            ajaxRequest('/Home/Hotel/addHotel', param, 'post', null, null, $me);
        }else{
            ajaxRequest('/Home/Hotel/addCharityHotel', param, 'post', null, null, $me);
        };
    });
    // 添加客栈自动校验
//  $('#addHotelModal .modal-content').inputValidate({
//      submit: {
//          query: '#submitAddCharity'
//      },
//      inputs: [{
//          query: '#hotelName',
//          regexp: window.commonRegexp.nameLength20,
//          message: lang('dealer.name'),
//          emptyMessage: lang('tip.popularizeNull')
//      }]
//  });
    // 添加客栈
//  $('#submitAddCharity').on('successSubmit.amos.inputValidate', function(e) {
//      var param = {
//              hotel: $('#hotelName').val().trim(),
//              city: $('#cityContainer').find('.tag-selected-container .tag:last-child').data('value'),
//              district: $('#districtContainer').find('.tag-selected-container .tag:first-child').data('value'),
//              universalTime: $('#addHotelModal #addRequestUniversalTime').val()
//          },
//          $me = $(this);
//      if (!param.city || !param.district) {
//          formInlineTip($me, lang('dealer.checkAddress'));
//          return false;
//      }
//      formInlineRight($me);
//      ajaxRequest('/Home/Hotel/addCharityHotel', param, 'post', null, null, $me);
//  });    
    // 修改客栈自动校验
    $('#editHotelModal').inputValidate({
        submit: {
            query: '#submitEditHotel'
        },
        inputs: [{
            query: '#editHotelName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('dealer.name'),
            emptyMessage: lang('tip.popularizeNull')
        }]
    });
    // 修改客栈
    $('#submitEditHotel').on('successSubmit.amos.inputValidate', function(e) {
        var start_time = $('#requestStartTime').val();
        var end_time = $('#requestEndTime').val();
        var end_split = $('#select-splittime').find('option:selected').val();
        var currentHotel = $('#editHotelModal').data('id');
        var param = {
                hotel: currentHotel,
                name: $('#editHotelName').val().trim(),
                city: $('#editCityContainer').find('.tag-selected-container .tag:last-child').data('value'),
                district: $('#editDistrictContainer').find('.tag-selected-container .tag:first-child').data('value'),
                universalTime: $('#editHotelModal #editRequestUniversalTime').val(),
                checkinTime: start_time,
                checkoutTime: end_time,
                splitTime: end_split,
            },
            $me = $(this);
        if(getReg(end_time) || getReg(start_time) || getReg(end_split)){
            formInlineTip($me, lang('hoteltime'));
            return false;
        }else{
            if(getCompareTime(start_time,end_time)){
               formInlineTip($me, lang('hoteltimetip'));
               return false;
            }else{
               $me.closest('.form-group').removeClass('has-error');
            }
        };
        if(splitTimeRang(end_split)){
            formInlineTip($me, lang('splitrangtime'));
            return false;
        }
        if (!param.city || !param.district) {
            formInlineTip($me, lang('dealer.checkAddress'));
            return false;
        }
        formInlineRight($me);
        ajaxRequest('/Home/Hotel/editHotel', param, 'post', null, null, $me);
    });
    $('#disableHotelBtn').on('click', function() {
        var param = {
                hotel: window.currentHotel,
                status: 1
            },
            $me = $(this);
        ajaxRequest('/Home/Hotel/toggleUse', param, 'post', null, null, $me);
    });
    $('#enableHotelBtn').on('click', function() {
        var param = {
                hotel: window.currentHotel,
                status: 0
            },
            $me = $(this);
        ajaxRequest('/Home/Hotel/toggleUse', param, 'post', null, null, $me);
    });
    var addRoomTemplate = $('#addRoomTemplate');
    $('#editModal').on('show.bs.modal', function(e) {
        var $me = $(e.relatedTarget),
            $parent = $me.parents('tr'),
            modal = $(this),
            currentRoom = $me.parents('td').data('num');
        currentRoom = (currentRoom + '').split(',');
        $('#editRoomNumContainer').html('');
        window.dynamicRoom = [];
        for (var index in currentRoom) {
            var template = $(addRoomTemplate.clone().html());
            currentRoom[index] = currentRoom[index].split(':');
            template.attr('data-id', currentRoom[index][0]).find('input.roomNumInput').attr('data-tip-object', '#submitEdit').attr('value', currentRoom[index][1]);
            $('#editRoomNumContainer').append(template.prop('outerHTML'));
            window.dynamicRoom.push(currentRoom[index][1]);
        }
        modal.find('#editName').val($parent.find('.roomTypeName').text());
        modal.find('#editPrice').val($parent.find('.roomTypePrice').text());
        modal.find('#editCharityPrice').val($parent.find('.roomTypeCharityPrice').text());
        operatingType = $parent.data('value');
        formInlineRight($('#editName'));
        formInlineRight($('#editPrice'));
        formInlineRight($('#editCharityPrice'));
        formInlineRight($('#editRoomNumContainer'));
        var submitBtn = $('#submitEdit');
        formInlineRight(submitBtn);
        refreshQRMContainer(modal);
    });
    $('#deleteModal').on('show.bs.modal', function(e) {
        var triggerTd = $(e.relatedTarget).parents('td'),
            triggerTr = triggerTd.parents('tr');
        var roomType = triggerTd.data('type');
        var roomNum = triggerTr.find('.roomNumbers').data('roomnumber');
        $('#deleteModal .roomType').html(roomType);
        $('#deleteModal .roomNum').html(roomNum);
        operatingType = triggerTr.data('value');
        formInlineRight($('#submitDelete'));
    });
    // 添加房型
    $('#addModal').on('show.bs.modal', function(e) {
        var modal = $(this);
        $('#addName').val('');
        $('#addPrice').val('');
        $('#addCharityPrice').val('');
        formInlineRight($('#addName'));
        formInlineRight($('#addPrice'));
        formInlineRight($('#addCharityPrice'));
        formInlineRight($('#addRoomNumContainer'));
        var submitBtn = $('#submitAdd');
        formInlineRight(submitBtn);
        var template = $(addRoomTemplate.clone().html());
        template.find('.roomNumInput').attr('data-tip-object', '#submitAdd');
        $('#addRoomNumContainer').html(template.prop('outerHTML'));
        window.dynamicRoom = [];
        refreshQRMContainer(modal);
    });
    $('#addRoomNumTrigger').on('click', function(e) {
        var size = $('#addRoomNumContainer').find('.addRoomNum').size();
        if (size >= 50) {
            return false;
        }
        var template = $(addRoomTemplate.clone().html());
        template.find('.roomNumInput').attr('data-tip-object', '#submitAdd');
        $('#addRoomNumContainer').append(template.prop('outerHTML'));
    });
    $('#editRoomNumTrigger').on('click', function(e) {
        var size = $('#editRoomNumContainer').find('.addRoomNum').size();
        if (size >= 50) {
            return false;
        }
        var template = $(addRoomTemplate.clone().html());
        template.find('.roomNumInput').attr('data-tip-object', '#submitEdit');
        $('#editRoomNumContainer').append(template.prop('outerHTML'));
    });
    // 添加房型自动校验
    if (window.hotelUsage == 4) {
        $('#addModal').inputValidate({
            submit: {
                query: '#submitAdd'
            },
            inputs: [{
                query: '#addName',
                regexp: window.commonRegexp.nameLength15,
                message: lang('type.name'),
                emptyMessage: lang('type.nameNull')
            }, {
                query: '#addPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.price')
            }, {
                query: '#addCharityPrice',
                regexp: window.commonRegexp.roomTypeCharityPrice,
                message: lang('type.charityPay'),
                emptyMessage: lang('type.charityPrice')
            }]
        });            
    } else {
        $('#addModal').inputValidate({
            submit: {
                query: '#submitAdd'
            },
            inputs: [{
                query: '#addName',
                regexp: window.commonRegexp.nameLength15,
                message: lang('type.name'),
                emptyMessage: lang('type.nameNull')
            }, {
                query: '#addPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.price')
            }, {
                query: '#addCharityPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.charityPrice')
            }]
        });
    }

    // 添加房型提交请求
    $('#submitAdd').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var $me = $(this),
            param = {
                room: getRoomNumbers($('#addRoomNumContainer'), 'add')
            };
        if (param.room === false) {
            formInlineTip($me, lang('type.num'));
            return false;
        }
        formInlineRight($me);
        param.hotel = window.currentHotel;
        param.name = $('#addName').val().trim();
        param.price = $('#addPrice').val().trim();
        if ($('#addCharityPrice').val()) {
            param.charityPrice = $('#addCharityPrice').val().trim();
        }
        ajaxRequest('/Home/Room/addRoom', param, 'post', null, operateRoomTypeErrorCallback, $me);
    });
    var operatingType = 0;
    // 修改房型自动校验
    if (window.hotelUsage == 4) {
        $('#editModal').inputValidate({
            submit: {
                query: '#submitEdit'
            },
            inputs: [{
                query: '#editName',
                regexp: window.commonRegexp.nameLength15,
                message: lang('type.name'),
                emptyMessage: lang('type.nameNull')
            }, {
                query: '#editPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.price')
            }, {
                query: '#editCharityPrice',
                regexp: window.commonRegexp.roomTypeCharityPrice,
                message: lang('type.charityPay'),
                emptyMessage: lang('type.charityPrice')
            }]
        });           
    } else {
        $('#editModal').inputValidate({
            submit: {
                query: '#submitEdit'
            },
            inputs: [{
                query: '#editName',
                regexp: window.commonRegexp.nameLength15,
                message: lang('type.name'),
                emptyMessage: lang('type.nameNull')
            }, {
                query: '#editPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.price')
            }, {
                query: '#editCharityPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.charityPrice')
            }]
        });
    }
    
    var constructCalendar = function(year,month,data){
    	var daysInfos = calendar.getMonthData(year,month);
    	var html_days = new Array();
    	var html_week = '';
    	for(var i=0; i<daysInfos.length; i++){
    		var cell_type = '';
    		var dayInfo = daysInfos[i];
    		
    		if(dayInfo.isOverdue){
    			cell_type += ' day_overdue';
    		}
    		
    		var timestamp = dayInfo.timestamp;
    		var center_content = window.symbols;
    		if(data){
    	    	var price = data['price'];
                var rackRate = price;//门市价
    	    	if(data['price_list'][timestamp]){
    	    		price = data['price_list'][timestamp]['price'];
                    rackRate = data['price_list'][timestamp]['shopPrice'] ? data['price_list'][timestamp]['shopPrice'] : price;
    	    		cell_type += ' price_change';
    	    	}
    	    	price = parseInt(price); 
    	    	center_content += price;
    		}
    		if(dayInfo.festival){
    			cell_type += ' day_festival';
    		}
    		
    		var right_top = dayInfo.dayNum;
    		if(dayInfo.dayNum==1){
    		    var monthNum = 'month.'+dayInfo.monthNum;
    			right_top = lang(monthNum) +'&nbsp;&nbsp;'+right_top;
    		}
    		var right_bottom = '';
    		if(dayInfo.isToday){
    			cell_type += ' day_today';
    			right_bottom = lang('today');
    		}
    		
    		var left_bottom = '';
    		if(dayInfo.isHoliday){
    			cell_type += ' day_holiday';
    			left_bottom = lang('type.recess');
    		}
            // 对于动态添加的项显示tooltip
            $('body').delegate('[data-toggle="tooltip"]', 'mouseover', function() {
                $(this).tooltip('show');
            });

    		html_week += '<td data-day="'+timestamp+'" data-overdue="'+dayInfo.isOverdue+'" data-price="'+rackRate+'" class="' + cell_type;
            if(data['price_list'][timestamp]){
                if(data['price_list'][timestamp].hasOwnProperty('last')){
                    title = '<span class="tuli-tag-status">'+data['price_list'][timestamp]['start']+lang("take.effect")+'</span><br />'
                    +'<span class="tuli-tag-status">'+data['price_list'][timestamp]['end']+lang("end")+'</span><br />'
                    +'<span class="tuli-tag-status">'+lang("depreciate")+window.symbols+data['price_list'][timestamp]['decPrice']+'</span>';
                    html_week += '"id="last-room" data-toggle="tooltip" data-placement="bottom" data-container="#doc-body" data-html="true" title='+"'"+title+"'>";
                ;
                    }else{
                    html_week += '">';
                }
            }else{
                html_week += '">';
            }
    		html_week += '<span class="center_content">' + center_content;
            if(data['price_list'][timestamp]){
                if(data['price_list'][timestamp].hasOwnProperty('last')){
                    html_week += '<i class="'+lang('ico-sale')+'"></i></span>';
                }else{
                    html_week += '</span>';
                }
            }else{
                html_week += '</span>';
            }
    		html_week += '<span class="left_top">' + dayInfo.festival + '</span>';
    		html_week += '<span class="right_top">' + right_top + '</span>';
    		html_week += '<span class="right_bottom">' + right_bottom + '</span>';
    		html_week += '<span class="left_bottom">' + left_bottom + '</span>';
    		html_week += '</td>';
    		if((i+1)%7==0){
    			html_days[parseInt(i/7)] = '<tr>'+html_week+'</tr>';
    			html_week = '';
    		}
    	}
    	$('#calendar_days').html(html_days.join());
    	$('#price_calendar .price_calendar_title').html($('#calendar_months').data('roomTypeName') + ' -'+lang('type.calendar'));
        $('#price_last_roomtype').html($('#calendar_months').data('roomTypeName'));
    };
    //显示价格日历
    var showCalendar = function(roomTypeId,year,month){
    	var param = {};
        param.hotel = window.currentHotel;
        param.roomtype_id = roomTypeId;
        ajaxRequest('/Home/Room/getPriceList', param, 'post', function(result){
        	constructCalendar(year, month, result.data);
        }, function(error) {
        	constructCalendar(year, month, null);
        	$('#price_calendar .err_info').html(lang('tip.server'));
        });
    }
    //显示预设价格
    $('#roomTypeList').on('click', '.priceCalendar', function(e) {
        var roomTypeId = $(this).parents('tr').data('value');
    	//显示月份
        var month = calendar.getMonthArray();
    	var html_month = "";
    	for(var i=0; i<month.length; i++){
    		var style = i==0?' class="selected"':'';
    		html_month += '<tr' + style + '><td data-year="'+ month[i].year +'" data-month="'+ month[i].month +'"><span>' + month[i].year + lang('calendar.years') + month[i].month + lang('calendar.months')+'</span></td></tr>';
    	}
    	$('#calendar_months').html(html_month).data('roomTypeId',roomTypeId).data('roomTypeName',$(this).parent().parent().find('.roomTypeName').html());    	
        //显示日历框
    	$('#price_calendar').modal('show');
    	//请求价格数据并显示 
        showCalendar(roomTypeId, month[0].year, month[0].month);
    });
    //切换月份
    $('#calendar_months').on('click','td',function(){
    	$(this).parent().addClass('selected').siblings().removeClass('selected');
    	var roomTypeId = $('#calendar_months').data('roomTypeId');
    	var year = $(this).data('year');
    	var month = $(this).data('month');
    	showCalendar(roomTypeId, year, month);
    });
    //设置价格输入框
    $('#calendar_days').on('click','td',function(){
    	if($(this).data('overdue')){
    		return;
    	}
    	$(this).addClass('selected');
    	$('#price_input').val('').data('price_date', $(this).data('day'));
    	$('#set_price_info').html('');
    	$('#price_calendar_set').modal('show');
    });
    //输入框焦点
    $('#price_calendar_set').on('shown.bs.modal', function (e) {
    	$('#price_input').focus();
    });
    //关闭事件
    $('#price_calendar_set').on('hide.bs.modal', function (e) {   
    	$('#calendar_days').find('td').removeClass('selected');
    });
    //设置价格
    $('#set_price').on('click',function(){ 
    	var param = {};
        param.hotel = window.currentHotel;
    	param.roomtype_id = $('#calendar_months').data('roomTypeId');
    	param.price_date = $('#price_input').data('price_date');
    	param.price = $('#price_input').val();
        param.orig = $("#calendar_days [data-day="+param.price_date+"]").data('price');
    	var reg = new RegExp('(^[1-9][0-9]{0,5}$)');
    	if(!reg.test(param.price)){        	
        	$('#set_price_info').html(lang('type.paywrong')); 
        	$('#price_input').focus();   		
    		return;
    	}
    	ajaxRequest('/Home/Room/setPrice', param, 'post', function(data){
    		$('#price_calendar_set').modal('hide');
        	var roomTypeId = $('#calendar_months').data('roomTypeId');
        	var year = $('#calendar_months .selected td').data('year');
        	var month = $('#calendar_months .selected  td').data('month');
    		showCalendar(roomTypeId, year, month);
        }, function(error) {
            if(error.responseJSON.info != undefined){
                $('#set_price_info').html(error.responseJSON.info);
            }else{
                $('#set_price_info').html(lang('tip.server'));
            }
        });    	
    });
    //尾房特卖 相关
    var format = 'YYYY-MM-DD';
    var nowadays =  $('#doc').data('today'); 
    var tomorrow = $('#doc').data('tomorrow'); 
    var month = new Date();
    month.setMonth(month.getMonth()+1);
    var  nextMonth =  month.toLocaleDateString().replace(/\//g,'-');
    $('#datePicker').find('.start').html(nowadays);
    $('#datePicker').find('.end').html(tomorrow);
    $('#datePickerInput').daterangepicker({
        'showDropdowns': true,
        'autoApply': true,
        'dateLimit': {
            'days': 30
        },
        'locale': {
            'format': format,
            'applyLabel': lang('date.ensure'),
            'cancelLabel': lang('date.cancel'),
            'daysOfWeek': [
                lang('week.7'),
                lang('week.1'),
                lang('week.2'),
                lang('week.3'),
                lang('week.4'),
                lang('week.5'),
                lang('week.6')
            ],
            'monthNames': [
                lang('month.1'),
                lang('month.2'),
                lang('month.3'),
                lang('month.4'),
                lang('month.5'),
                lang('month.6'),
                lang('month.7'),
                lang('month.8'),
                lang('month.9'),
                lang('month.10'),
                lang('month.11'),
                lang('month.12')
            ],
            'firstDay': 1
        },
        'linkedCalendars': false,
        'parentEl': 'body',
        'startDate': nowadays,
        'endDate': tomorrow,
        'minDate': nowadays,
        'maxDate': nextMonth,
        'opens': 'center'
    }, function (start, end, label) {
        $('#datePicker').find('.start').html(start.format(format));
        $('#datePicker').find('.end').html(end.format(format));
    });
    $('#datePickerContainer').on('click', function () {
        $('#datePickerInput').trigger('focus');
    });
    var showLastRoom = function (data) {
        if(data===false){
            $('#decRMB').val('');
            $('#datePicker').find('.start').html(nowadays);
            $('#datePicker').find('.end').html(tomorrow);
            $(".price-time-select").val("0");
            $('#clearLastRoom').addClass('hidden');
            $('#clearLastRoom').data('id',0);
        }else{
            $('#decRMB').val(parseInt(data.price));
            $('#datePicker').find('.start').html(data.startdate);
            $('#datePicker').find('.end').html(data.enddate);
            $("#startTime").val(data.starttime);
            $("#endTime").val(data.endtime);
            $('#clearLastRoom').removeClass('hidden');
            $('#clearLastRoom').data('id',data.id);
        }
    }
    
    $('#decRMB').blur(function () {
        var price =$(this).val().replace(/^0/g,'');
        $(this).val(price);
        if(price.length != '' && !/^[1-9][0-9]{0,5}$/.test(price)){
            $('#div-set-room-price').addClass('has-error');
            $('#set-room-price').text(lang('supportinteger'));
            return false;
        }
    })
    $("#price_calendar_last_room").on('click', function () {
        $('#addLastRoomModel').modal('show');
        var param = {
                hotel: window.currentHotel,
                roomTypeId : $('#calendar_months').data('roomTypeId'),
            },$me = $(this);
        ajaxRequest('/Home/Room/getLastRoomRrice', param, 'post', function(data){
            $('#div-set-room-price').removeClass('has-error');
            if(data.data.length===0){
                showLastRoom(false);
            }else{
                showLastRoom(data.data);
            }
        }, null, $me);
    });


    $('#submitLastRoom').on('click', function () {
        var price =$('#decRMB').val();
        if(price.length == 0){
            $('#div-set-room-price').addClass('has-error');
            $('#set-room-price').text(lang('depreciatePrice'));
            return false;
        }
        if(price.length != '' && !/^[1-9][0-9]{0,5}$/.test(price)){
            $('#div-set-room-price').addClass('has-error');
            $('#set-room-price').text(lang('supportinteger'));
            return false;
        }
        var param = {
                hotel: window.currentHotel,
                roomTypeId: $('#calendar_months').data('roomTypeId'),
                price: price,
                startDate: $('#datePicker').find('.start').text(),
                endDate: $('#datePicker').find('.end').text(),
                startTime: $("#startTime").val(),
                endTime : $("#endTime").val(),
            },$me = $(this);
        if($('#clearLastRoom').data('id')){
            param.id=$('#clearLastRoom').data('id');
        }
        var startDateTimestamp = new Date(param.startDate.replace(/-/g,'/')).getTime()/1000; //转换成时间戳
        var endDateTimestamp = new Date(param.endDate.replace(/-/g,'/')).getTime()/1000; //转换成时间戳
        for (var i = startDateTimestamp; i <= endDateTimestamp; i+=86400) {
            var price = $("#calendar_days [data-day="+i+"]").data('price');
            if(parseInt(price)<parseInt(param.price)){
                $('#div-set-room-price').addClass('has-error');
                $('#set-room-price').text(lang('pricemax'));
                return false;
            }
        }
        if(param.startDate == param.endDate && parseInt(param.startTime) >= parseInt(param.endTime)){
            $('#div-set-room-price').addClass('has-error');
            $('#set-room-price').text(lang('start.max'));
            return false;
        }
        if(parseInt(param.startTime) == parseInt(param.endTime)){
            $('#div-set-room-price').addClass('has-error');
            $('#set-room-price').text(lang('start.equal'));
            return false;
        }
        ajaxRequest('/Home/Room/addLastRoomRrice', param, 'post', function(data){
            $('#addLastRoomModel').modal('hide');
            var year = $('#calendar_months .selected').find("td").data('year');
            var month = $('#calendar_months .selected').find("td").data('month');
            showCalendar(param.roomTypeId, year, month);
        }, null, $me);
    });
    $('#clearLastRoom').on('click', function () {
        var param = {
                hotel: window.currentHotel,
                id: $('#clearLastRoom').data('id')
            },$me = $(this);
        if($('#clearLastRoom').data('id')){
            param.id=$('#clearLastRoom').data('id');
        }
        ajaxRequest('/Home/Room/delLastRoomRrice', param, 'post', function(data){
            $('#addLastRoomModel').modal('hide');
            var year = $('#calendar_months .selected').find("td").data('year');
            var month = $('#calendar_months .selected').find("td").data('month');
            showCalendar($('#calendar_months').data('roomTypeId'), year, month);
        }, null, $me);
    });
    // 修改房型
    $('#submitEdit').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        var $me = $(this),
            param = {
                rooms: getRoomNumbers($('#editRoomNumContainer'))
            };
        if (param.rooms === false) {
            formInlineTip($me, lang('type.num'));
            return false;
        }
        formInlineRight($me);
        param.rooms = JSON.stringify(param.rooms);
        param.hotel = window.currentHotel;
        param.name = $('#editName').val().trim();
        param.room = operatingType;
        param.price = $('#editPrice').val().trim();
        if ($('#editCharityPrice').val()) {
            param.charityPrice = $('#editCharityPrice').val().trim(); 
        }
        ajaxRequest('/Home/Room/editRoom', param, 'post', null, operateRoomTypeErrorCallback, $me);
    });

    // 删除房型
    $('#submitDelete').on('click', function(e) {
        var param = {
                hotel: window.currentHotel,
                room: operatingType
            },
            $me = $(this);
        ajaxRequest('/Home/Room/deleteRoom', param, 'post', null, function(error, $obj) {
            if (typeof error.responseJSON == 'undefined') {
                formInlineTip($obj, lang('tip.networkPoor'));
            } else {
                formInlineTip($obj, error.responseJSON.info);
            }
        }, $me);
    });
    // 登录锁掌柜参数校验
    $('#qrmLoginModel').inputValidate({
        submit: {
            query: '#submitQrmLogin'
        },
        inputs: [{
            query: '#qrmLoginPassword',
            regexp: window.commonRegexp.QRMPassword,
            message: lang('tip.password'),
            emptyMessage: lang('tip.passwordNull')
        }]
    });
    // 登录锁掌柜
    $('#submitQrmLogin').on('successSubmit.amos.inputValidate', function() {
        var loginName = qrmLoginMethod === 'mobile' ? $('#qrmLoginNameMobile').val().trim() : $('#qrmLoginNameEmail').val().trim();
        if (!window.commonRegexp.globalMobile.test(loginName) && !window.commonRegexp.email.test(loginName) || !window.commonRegexp.nameLength50.test(loginName)) {
            if (qrmLoginMethod === 'mobile') {
                formInlineTip($('#qrmLoginNameMobile'), lang('tip.phoneForma'));
            } else {
                formInlineTip($('#qrmLoginNameEmail'), lang('tip.mailbox'));
            }
            return false;
        }
        formInlineRight($('#qrmLoginNameMobile'));
        var param = {
                hotel: window.currentHotel,
                password: $('#qrmLoginPassword').val().trim()
            },
            $me = $(this);
        if (qrmLoginMethod === 'mobile') {
            param.mobile = loginName;
            param.areaCode = $('#qrmLoginModel #areaCodeValue').text().trim();
        } else {
            param.email = loginName;
        }
        ajaxRequest('/Home/Hotel/qrmLogin', param, 'post', function(data) {
            var tagsData = [];
            $.each(data.data, function(index, community) {
                tagsData.push({
                    id: community.no,
                    name: community.name + '-' + community.type
                });
            });
            $('#communitiesContainer').tag({
                removeAtSelected: false,
                selectedTagClickable: false,
                avaliable: tagsData
            }).on('selectedClick.amos.tag', function(e, selectedIndex) {
                var communitiesContainer = $(this);
                communitiesContainer.tag('resetSelected');
                communitiesContainer.find('.tag-avaliable-container').removeClass('hidden');
                $('#submitBindCommunity').removeData('value');
                formInlineRight($('#submitBindCommunity'));
            }).on('beforeSelected.amos.tag', function(e, value) {
                var communitiesContainer = $(this);
                communitiesContainer.find('.tag-avaliable-container').addClass('hidden');
                $('#submitBindCommunity').data('value', value);
                formInlineRight($('#submitBindCommunity'));
            });
            $('#loginContent').addClass('hidden');
            $('#bindCommunityContent').removeClass('hidden');
        }, null, $me);
    });
    // 绑定集群
    $('#submitBindCommunity').on('click', function() {
        var $me = $(this),
            param = {
                hotel: window.currentHotel,
                community: $me.data('value')
            };
        if (param.community === undefined || param.community === 0) {
            formInlineTip($me, lang('type.colony'));
            return false;
        }

        ajaxRequest('/Home/Hotel/bindCommunity', param, 'post', function(data, submitBtn) {
            formInlineTip(submitBtn, lang('type.bindSucceed'), 1);
            window.setTimeout(function() {
                window.qrmInit = data.data;
                $('#qrmLoginModalTrigger').remove();
                $('#qrmLoginModel').modal('hide');
                // 刷新可同步锁掌柜房间
                refreshQrmSynRoom();
            }, 1000);
        }, null, $me);
    });
    var roomRemove = function(e) {
        var trigger = $(this);
        var size = trigger.parents('.roomNumContainer').find('.addRoomNum').size();
        if (size == 1) {
            return false;
        }
        var modal = trigger.parents('.modal');
        trigger.parents('.addRoomNum').remove();
        refreshQRMContainer(modal);
    };
    $('.modal').on('input', '.roomNumInput', function(e) {
        var currentInput = $(this);
        var modal = currentInput.parents('.modal');
        var currentValue = currentInput.val();
        if (currentValue !== '') {
            var sameValueInput = 0;
            modal.find('.roomNumInput').each(function(index) {
                var input = $(this);
                if (input.val() == currentValue) {
                    sameValueInput++;
                }
            });
            if (sameValueInput > 1) {
                formInlineTip(currentInput, lang('type.norepeat'));
            }
        }
        refreshQRMContainer(modal);
    });
    $('#addRoomNumContainer').on('click', '.addRoomNum .iconfont', roomRemove).on('mouseenter', '.addRoomNum', function(e) {
        $(this).addClass('hover');
    }).on('mouseleave', '.addRoomNum', function(e) {
        $(this).removeClass('hover');
    });
    $('#editRoomNumContainer').on('click', '.addRoomNum .iconfont', roomRemove).on('mouseenter', '.addRoomNum', function(e) {
        $(this).addClass('hover');
    }).on('mouseleave', '.addRoomNum', function(e) {
        $(this).removeClass('hover');
    });
    //城市初始化
    var getCitys = function(cityContainer){
        var data = cityContainer.data('amos.tag');
        if (!data) {
            cityContainer.tag({
                removeAtSelected: true,
                selectedTagClickable: false,
                avaliable: window.cityList
            });
            cityContainer.on('selectedClick.amos.tag', selectedClickCity);
            cityContainer.on('beforeSelected.amos.tag', beforeSelectedCity);
        } else {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityList);
        }
        var districtContainer = $('#districtContainer');
        var editDistrictContainer = $('#editDistrictContainer');
            editDistrictContainer.tag('resetSelected');
            editDistrictContainer.tag('resetAvaliable');
        data = districtContainer.data('amos.tag');
        if (!data) {
            districtContainer.tag({
                removeAtSelected: false,
                selectedTagClickable: false
            });
            districtContainer.on('selectedClick.amos.tag', selectedClickDistrict);
            districtContainer.on('beforeSelected.amos.tag', beforeSelectedDistrict);
            districtContainer.tag('resetAvaliable');
        } else {
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
        };     
    };
    $('#addHotelModal').on('show.bs.modal', function(e) {
        window.cityList = citylistArr[4];
        getCitys($('#cityContainer'));
    });
    $("#addHotelModal #addRequestUniversalTime").change(function(){
        var cityId =parseInt($(this).val())-1 ;
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityList = citylistArr[i]; 
            }
        }
        getCitys($('#cityContainer'));
    });
    $("#editHotelModal #editRequestUniversalTime").change(function(){
        var cityId =parseInt($(this).val())-1 ;
        
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityList = citylistArr[i]; 
            }
        }
        getCitys($('#editCityContainer'));
    });
    $('#editHotelModal').on('show.bs.modal', function(e) {
        var trigger = $(e.relatedTarget);
        var selected = [];
        var cityId = trigger.data('city');
        var universaltimeId = trigger.data('universaltimeid');
        $("#requestStartTime").val(trigger.data('start'));
        $("#requestEndTime").val(trigger.data('end'));
        $('#editHotelModal').data('id',trigger.data('id'))
        $("#editHotelModal #editRequestUniversalTime").val(universaltimeId);
        $('#editHotelName').val(trigger.data('name'));
        $("#select-splittime option").map(function(){
            if ($(this).val() == trigger.data('splittime')) {
                $(this).attr("selected",true);
            }
        });
        window.cityList = citylistArr[parseInt(universaltimeId-1)];
        var cityPath = getCityPath(cityId);
        selected.push({
            'id': cityPath.province.id,
            'name': cityPath.province.name
        });
        selected.push({
            'id': cityId,
            'name': cityPath.city.name
        });
        var cityContainer = $('#editCityContainer');
        var data = cityContainer.data('amos.tag');
        if (!data) {
            cityContainer.tag({
                removeAtSelected: true,
                selectedTagClickable: false,
                selected: selected
            });
            cityContainer.on('selectedClick.amos.tag', selectedClickCity);
            cityContainer.on('beforeSelected.amos.tag', beforeSelectedCity);
            cityContainer.tag('resetAvaliable');
        } else {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addSelected', selected);
        }
        var districtSelected = [];
        districtSelected.push({
            'id': trigger.data('district'),
            'name': trigger.data('districtname')
        });
        var districtContainer = $('#editDistrictContainer');
        data = districtContainer.data('amos.tag');
        if (!data) {
            districtContainer.tag({
                removeAtSelected: false,
                selectedTagClickable: false,
                selected: districtSelected
            });
            districtContainer.on('selectedClick.amos.tag', selectedClickDistrict);
            districtContainer.on('beforeSelected.amos.tag', beforeSelectedDistrict);
            districtContainer.tag('resetAvaliable');
        } else {
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
            districtContainer.tag('addSelected', districtSelected);
        }
        var params = {};
        params.city = cityId;
        ajaxRequest('/Home/Position/getDistrict', params, 'post', function(data) {
            if (data !== undefined) {
                districtContainer.tag('addAvaliable', data.data);
            }
            districtContainer.find('.tag-avaliable-container').addClass('hidden');
        }, null);
    });
    // 获取房间名
    var getRoomNumbers = function($container, operation) {
        var returnValue = [],
            valueRecord = [],
            hasError = false;
        $container.find('input.roomNumInput').each(function() {
            var value = $(this).val().trim();
            // 格式通过而且没有push过
            if (window.commonRegexp.nameLength15.test(value) === false) {
                hasError = true;
            }
            if (valueRecord.indexOf(value) != -1 || value === '') {
                formInlineTip($(this), lang('type.roomNum'));
                hasError = true;
            }
            if (!hasError) {
                if (operation == 'add') {
                    returnValue.push(value);
                    valueRecord.push(value);
                } else {
                    var id = $(this).parents('.addRoomNum').data('id');
                    returnValue.push({
                        id: id ? id : 0,
                        name: value
                    });
                    valueRecord.push(value);
                }
            }
        });
        if (operation == 'add') {
            returnValue = returnValue.join(',');
        }
        if (!hasError) {
            formInlineRight($container.find('input.roomNumInput'));
            return returnValue;
        }
        return false;
    };
    var selectedClickCity = function(e, selectedIndex) {
        var cityContainer = $(this);
        var selectedTag = $(e.relatedTarget);
        // 0表示选择省份，1表示选择城市
        if (selectedIndex === 0) {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityList);
        } else {
            selectedTag.remove();
            cityContainer.tag('resetAvaliable');
            var value = cityContainer.find('.tag-selected-container .tag').data('value');
            var selectedProvinceCityList = getProvinceCities(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        }
        var districtContainer = cityContainer.parents('form').find('.districtContainer');
        districtContainer.tag('resetSelected');
        districtContainer.tag('resetAvaliable');
    };
    var beforeSelectedCity = function(e, value) {
        var cityContainer = $(this);
        var selectedSize = cityContainer.find('.tag-selected-container .tag').size();
        // 0表示选择省份，1表示选择城市
        cityContainer.tag('resetAvaliable');
        if (selectedSize === 0) {
            var selectedProvinceCityList = getProvinceCities(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        } else {
            getCityDistricts(value, cityContainer);
        }
    };
    var selectedClickDistrict = function(e, selectedIndex) {
        var districtContainer = $(this);
        districtContainer.tag('resetSelected');
        districtContainer.find('.tag-avaliable-container').removeClass('hidden');
    };
    var beforeSelectedDistrict = function(e, value) {
        var districtContainer = $(this);
        districtContainer.find('.tag-avaliable-container').addClass('hidden');
    };
    var getCityDistricts = function(value, cityContainer) {
        var params = {};
        params.city = value;
        ajaxRequest('/Home/Position/getDistrict', params, 'post', function(data, cityContainer) {
            var districtContainer = cityContainer.parents('form').find('.districtContainer');
            districtContainer.find('.tag-avaliable-container').removeClass('hidden');
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
            if (data !== undefined) {
                districtContainer.tag('addAvaliable', data.data);
            }
        }, null, cityContainer);
    };
    var getCityPath = function(cityId) {
        var cityPath = {};
        var selectedProvince = null;
        for (var i = 0; i < window.cityList.length; i++) {
            for (var j = 0; j < window.cityList[i].cities.length; j++) {
                if (window.cityList[i].cities[j].id === cityId) {
                    selectedProvince = window.cityList[i];
                    selectedCity = window.cityList[i].cities[j];
                    break;
                }
            }
            if (selectedProvince !== null) {
                break;
            }
        }
        cityPath.province = selectedProvince;
        cityPath.city = selectedCity;
        return cityPath;
    };
    var getProvinceCities = function(value) {
        var selectedProvinceCityList = [];
        for (var i = 0; i < cityList.length; i++) {
            if (cityList[i].id === value) {
                selectedProvinceCityList = cityList[i].cities;
                break;
            }
        }
        return selectedProvinceCityList;
    };
    
    // 停用启用客栈
    $('#roomTypeHotelList tr').each(function(e) {
        var btnTr = $(this);
        if(btnTr.data('stop') == 1){
            btnTr.find('span').addClass('stophotel');
        };
    });
    $('#roomTypeHotelList').on('click','.submitStopConfirm',function(e){
        var btnTr = $(this).closest('tr');
        var hotalid = btnTr.data('id');
        var  disableHotel = [];
        disableHotel.push(hotalid);
        ajaxRequest('/Home/Hotel/saveEnableStatus', { disableHotel: disableHotel}, 'POST', function(){
            btnTr.find('.submitStopConfirm').addClass('hidden');
            btnTr.find('.submitStartConfirm').removeClass('hidden');
            btnTr.find('.submitEditConfirm').addClass('hidden');
            btnTr.find('span').addClass('stophotel');
        }, null);
    });
    $('#roomTypeHotelList').on('click','.submitStartConfirm',function(e){
        var btnTr = $(this).closest('tr');
        var hotalid = btnTr.data('id');
        var  enableHotel = [];
        enableHotel.push(hotalid);
        ajaxRequest('/Home/Hotel/saveEnableStatus', { enableHotel: enableHotel}, 'POST', function(){
            btnTr.find('.submitStartConfirm').addClass('hidden');
            btnTr.find('.submitEditConfirm').removeClass('hidden');
            btnTr.find('.submitStopConfirm').removeClass('hidden');
            btnTr.find('span').removeClass('stophotel');
        }, null);
    });    
    //客栈时间
    $('#requestStartTime,#requestEndTime').on('focus',function(){
        $('.form-group').removeClass('has-error has-warning');
    }); 
    //引导页
    var firstGuidePage = $('.firstGuidePage');    
    ajaxRequest('/Home/GuidancePage/getGuidanceData',{
        'guidances':'night',
    }, 'post', function(data){
        if(data.data.night){
            firstGuidePage.removeClass('hidden');
        };
    },null);       
    firstGuidePage.on('click','.roger',function(e){
        ajaxRequest('/Home/GuidancePage/setGuidanceData', {
            'guidances':'night',
        }, 'post', function(data){
            firstGuidePage.addClass('hidden');
        });        
    });
    
});
var operateRoomTypeErrorCallback = function(error, $obj) {
    if (typeof error.responseJSON == 'undefined') {
        formInlineTip($obj, lang('tip.server'));
    } else if (error.responseJSON.status == 303 && error.status == 403 && error.responseJSON.data != 'error') {
        formInlineTip($obj, lang('type') + error.responseJSON.data + lang('type.exist'));
    } else {
        formInlineTip($obj, error.responseJSON.info);
    }
};

var getCompareTime = function(start,end){
    var timestamp_start = parseInt(start.split(':')[0])*60 + parseInt(start.split(':')[1]);
    var timestamp_end = parseInt(end.split(':')[0])*60 + parseInt(end.split(':')[1]);
    if(timestamp_start>timestamp_end){
        return false;
    }else{
        return true;
    }
};
var getReg = function(value){
    var reg = new RegExp(/^([0-1]{1}\d|2[0-3]):([0-5]\d)$/);
    if(reg.test(value)){
        return false;
    }else{
        return true;
    }
}
var splitTimeRang = function(value){
    var reg = new RegExp(/^(([0]{1}[0-5]{1}):([0-5]\d))|(([0]{1}[6]{1}):([0]{1}[0]{1}))$/);
    if(reg.test(value)){
        return false;
    }else{
        return true;
    }
}
